package com.limao.DBProvider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.limao.CacheManager.CrowdOrderCache;
import com.limao.CacheManager.CrowdSysProjectCache;
import com.limao.CacheManager.CrowdUserAuthCache;
import com.limao.CacheManager.VrGoodsCache;
import com.limao.DBDataClass.CrowdPrestigeGoodsDataClass;
import com.limao.DBDataClass.CrowdUserAuthClass;
import com.limao.DBDataClass.RedbagPrize;
import com.limao.DBDataClass.UserRedBagDataClass;
import com.limao.DBDataClass.VrGoodsDataClass;
import com.limao.DbConnection.DbConnectionManager;
import com.limao.Model.LzPluginException;
import com.limao.Tool.CacheClass;
import com.limao.push.SysRmbRecTypeEnum;


public class UserRedbagProvider {
	
	private static class DB_Adv_ProviderContainer {
		private static UserRedbagProvider instance = new UserRedbagProvider();
	}

	public static UserRedbagProvider getInstance() {
		return DB_Adv_ProviderContainer.instance;
	}
	
	// 初始化
	private UserRedbagProvider() {

	}
	
	
	private UserRedBagDataClass encapOrderData(ResultSet rs) throws Exception{
		
		UserRedBagDataClass orderData = new UserRedBagDataClass();
	
		orderData.userredbagid= rs.getString("userredbagid");
		orderData.touserid= rs.getString("touserid");
		orderData.buyuserid= rs.getString("buyuserid");
		orderData.buyusername= rs.getString("buyusername");
		orderData.redbagid= rs.getString("redbagid");
		orderData.level= rs.getString("level");
		orderData.orderid= rs.getString("orderid");
		orderData.state= rs.getString("state");
		orderData.createtime= rs.getString("createtime");
		orderData.endtime= rs.getString("endtime");
		orderData.rmb= rs.getString("rmb");
		orderData.prestigeorderid= rs.getString("prestigeorderid");
		orderData.opentime= rs.getString("opentime");
		
		orderData.redbagname= rs.getString("redbagname");
		orderData.redbagimage= rs.getString("redbagimage");

		return orderData;
		
	}

	
	public List<UserRedBagDataClass> Load_UserRedbagList(int userid) {
		
		ArrayList<UserRedBagDataClass> list = new ArrayList<UserRedBagDataClass>();
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement("select ur.*,sr.redbagname,sr.redbagimage from cd_user_redbag ur" +
					" left join cd_sys_redbag sr on sr.redbagid=ur.redbagid " +
					" where ur.touserid=? order by ur.userredbagid desc");
			pstmt.setInt(1, userid);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				list.add(encapOrderData(rs));
			}
		} catch (Exception e) {
			list.clear();
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return list;

	}
	
	
	public UserRedBagDataClass Load_UserRedbag(int userredbagid) {
		
		UserRedBagDataClass obj =null;
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement("select ur.*,sr.redbagname,sr.redbagimage from cd_user_redbag ur" +
					" left join cd_sys_redbag sr on sr.redbagid=ur.redbagid " +
					" where ur.userredbagid=? ");
			pstmt.setInt(1, userredbagid);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				obj=encapOrderData(rs);
			}
		} catch (Exception e) {
			obj=null;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return obj;

	}	
	
	
	
	public UserRedBagDataClass Load_UserRedbagByuseridRedbagid(int userredbagid,int userid) {
		
		UserRedBagDataClass obj =null;
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement("select ur.*,sr.redbagname,sr.redbagimage from cd_user_redbag ur" +
					" left join cd_sys_redbag sr on sr.redbagid=ur.redbagid " +
					" where ur.userredbagid=? and ur.touserid=? ");
			pstmt.setInt(1, userredbagid);
			pstmt.setInt(2, userid);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				obj=encapOrderData(rs);
			}
		} catch (Exception e) {
			obj=null;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return obj;

	}	
		
	
	public UserRedBagDataClass Update_UserRedbag(int userredbagid,RedbagPrize p) throws LzPluginException {
		
		boolean abortTransaction = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		UserRedBagDataClass tmp=Load_UserRedbag(userredbagid);
		if(tmp==null)
		{
			throw new LzPluginException("用户宝箱不存在。");
		}
		
		try {
			long time=CacheClass.getTime();
			int rmbtype=CacheClass.getIntValue(p.rmbtype); //奖品类型 0金额 1实物  2现货瓶数
			switch(rmbtype)
			{
			case 0:
				System.out.println(" 中奖为金额");
				con = DbConnectionManager.getTransactionConnection();
				//增加金额
				if(CacheClass.getFloatValue(p.rmb)>0)
				{
					pstmt = con.prepareStatement("update cd_user_rmb set nowrmb =(nowrmb +?) where userid=?");
					pstmt.setBigDecimal(1, CacheClass.toBigDecimal(p.rmb));
					pstmt.setInt(2, CacheClass.getIntValue(tmp.touserid));
					pstmt.executeUpdate();
					
					//取更新后的新值
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					String nowrmb="0";
					pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
					pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
					rs=pstmt.executeQuery();
					if(rs.next())
					{
						nowrmb=rs.getString("nowrmb");
					}
					
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid) VALUES (?,?,?,?,?,?,?,?,?,?)");
					pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
					pstmt.setInt(2, 0);
					pstmt.setFloat(3, CacheClass.getFloatValue(p.rmb));
					pstmt.setInt(4, 0);
					pstmt.setInt(5, SysRmbRecTypeEnum.type7.getIntVlue());  //宝箱打开得金额
					pstmt.setLong(6, time);
					pstmt.setString(7, "系统");
					pstmt.setString(8, "");
					pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
					pstmt.setLong(10, userredbagid); //宝箱id
					pstmt.execute();
				}
				
				
				//更新用户红包
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_redbag set state=1,opentime=?,rmb=? where  userredbagid=?");
				pstmt.setLong(1, time);
				pstmt.setFloat(2, CacheClass.getFloatValue(p.rmb));
				pstmt.setInt(3, userredbagid);
				pstmt.executeUpdate();
				
				break;
			case 1:
				System.out.println(" 中奖为实物");
				CrowdUserAuthClass authTmp= CrowdUserAuthCache.getInstance().getUser(CacheClass.getIntValue(tmp.touserid));
				int istest=CacheClass.getIntValue(authTmp.istest);
				//取得刚增加的奖品订单id
				long prestigeorderid=0;
				con = DbConnectionManager.getTransactionConnection();
				//取奖品商品
				if(CacheClass.getIntValue(p.prestigeid)>0)
				{
					CrowdPrestigeGoodsDataClass prestigegoods=null;
					pstmt = con.prepareStatement("select * from cd_sys_prestigegoods where prestigeid=? ");
					pstmt.setInt(1, CacheClass.getIntValue(p.prestigeid));
					rs=pstmt.executeQuery();
					if(rs.next())
					{
						prestigegoods =new CrowdPrestigeGoodsDataClass();
						prestigegoods.callbackprice=rs.getString("callbackprice");
						prestigegoods.iscanback=rs.getString("iscanback");
					}
					if(prestigegoods==null)
					{
						abortTransaction = true;
						throw new LzPluginException("奖品不存在。");
					}
					
					//增加奖品订单
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("insert into cd_sys_prestigeorder (userid,prestigeid,type,callbackprice,ctime,istest,iscanback) values (?,?,?,?,?,?,?) ");
					pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
					pstmt.setInt(2, CacheClass.getIntValue(p.prestigeid));
					pstmt.setInt(3, 3); //宝箱实物奖品订单
					pstmt.setFloat(4, CacheClass.getFloatValue(prestigegoods.callbackprice));
					pstmt.setLong(5, time);
					pstmt.setInt(6, istest);
					pstmt.setInt(7, CacheClass.getIntValue(prestigegoods.iscanback));
					pstmt.execute();
					

					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("select orderid from cd_sys_prestigeorder where userid=? and type=3 and ctime=?");
					pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
					pstmt.setLong(2, time);
					rs=pstmt.executeQuery();
					if(rs.next())
					{
						prestigeorderid=rs.getLong("orderid");
					}
					if(prestigeorderid==0)
					{
						abortTransaction = true;
						throw new LzPluginException("奖品订单不存在。");
					}
					
				}
				
				//更新用户红包
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_redbag set state=1,opentime=?,prestigeorderid=? where  userredbagid=?");
				pstmt.setLong(1, time);
				pstmt.setLong(2, prestigeorderid);
				pstmt.setInt(3, userredbagid);
				pstmt.executeUpdate();
				
				
				break;
			case 2:
				System.out.println(" 中奖为瓶数");
				con = DbConnectionManager.getTransactionConnection();
				if(CacheClass.getFloatValue(p.rmb)>0)
				{
					int vrgoodsid=0;
					VrGoodsDataClass vrgoods=VrGoodsCache.getInstance().Load_VrGoods_ByListFirst();
					if(vrgoods!=null)
					{
						vrgoodsid=CacheClass.getIntValue(vrgoods.vrgoodsid);
					}
					//购买人经验值增加 及 增加送的现货瓶数
					if(vrgoodsid>0)
					{
						//现货品种瓶数更新
						DbConnectionManager.fastcloseStmt(rs,pstmt);
						pstmt = con.prepareStatement("select * from cd_user_num where userid=? and vrgoodsid=? ;");
						pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
						pstmt.setInt(2, vrgoodsid);
						rs=pstmt.executeQuery();
						if(rs.next()) //存在 则更新
						{
							DbConnectionManager.fastcloseStmt(rs,pstmt);
							pstmt = con.prepareStatement("update cd_user_num set num=(num+?) where userid=? and vrgoodsid=? ;");
							pstmt.setBigDecimal(1, CacheClass.toBigDecimal(p.rmb));
							pstmt.setInt(2, CacheClass.getIntValue(tmp.touserid));
							pstmt.setInt(3, vrgoodsid);
							pstmt.executeUpdate();
							
						}
						else//不存在  则插入
						{
							DbConnectionManager.fastcloseStmt(rs,pstmt);
							pstmt = con.prepareStatement("insert into cd_user_num (userid,vrgoodsid,num) VALUES (?,?,?);");
							pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
							pstmt.setInt(2, vrgoodsid);
							pstmt.setBigDecimal(3, CacheClass.toBigDecimal(p.rmb));
							pstmt.execute();
							
						}
						
						
						//取更新后的新值
						String manowtotalrmb="0";
						DbConnectionManager.fastcloseStmt(rs,pstmt);
						pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
						pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
						pstmt.setInt(2, vrgoodsid);
						rs=pstmt.executeQuery();
						if(rs.next())
						{
							manowtotalrmb=rs.getString("num");
						}
						
						//增加现货瓶数变动记录
						DbConnectionManager.fastcloseStmt(rs,pstmt);
						pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
						pstmt.setInt(1, CacheClass.getIntValue(tmp.touserid));
						pstmt.setInt(2, 0);
						pstmt.setBigDecimal(3, CacheClass.toBigDecimal(p.rmb));
						pstmt.setInt(4, 0);
						pstmt.setInt(5, SysRmbRecTypeEnum.type103.getIntVlue());
						pstmt.setLong(6, time);
						pstmt.setString(7, "系统");
						pstmt.setString(8, "");
						pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb));
						pstmt.setLong(10, userredbagid);
						pstmt.setInt(11, vrgoodsid);
						pstmt.execute();
					}
				}
				
				
				//更新用户红包
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_redbag set state=1,opentime=?,goodsnum=? where  userredbagid=?");
				pstmt.setLong(1, time);
				pstmt.setFloat(2, CacheClass.getFloatValue(p.rmb));
				pstmt.setInt(3, userredbagid);
				pstmt.executeUpdate();
				
				break;
			}
			
			
		} catch (Exception e) {
			tmp=null;
			e.printStackTrace();
			abortTransaction=true;
			if(e instanceof LzPluginException)
			{
				throw new LzPluginException(e.getMessage());
			}
		} finally {
			DbConnectionManager.closeTransactionConnection(rs, pstmt, con, abortTransaction);
		}
		
		if(!abortTransaction) //成功
		{
			tmp=Load_UserRedbag(userredbagid);
			CrowdUserAuthCache.getInstance().ClearObjectCache(tmp.touserid+"");
			
		}
		else
			tmp=null;
		
		return tmp;

	}
	
	
}
